import {forEachValue} from "@/vuex/utils";
import Module from "@/vuex/module/module";

/*
root = {
  _raw: rootModule,
  state: rootModule.state,
  _children:{
    aCount: {
      _raw: aModule,
      state: aModule.state,
      _children:{
        cCount: {
          _raw: cModule,
          state:cModule.state,
          _children:{}
        }
      }
    },
    bCount: {
      _raw: bModule,
      state: bModule.state,
      _children:{}
    }
  }
}

root.state aCount.state bCount.state
*/
export default class ModuleCollection {
  constructor(rootModule) {
    this.root = null;
    this.register(rootModule, []);
  }

  register(rawModule,path){ //[] //[a] //[a,c]
    const newModule = new Module(rawModule);

    if (path.length === 0) { //是一个根模块
      this.root = newModule;

    } else {
      // [a,b,c]
      const parent = path.slice(0, -1/*最后一项是要添加的,最后第二项是parent,我们这里是找parent*/).reduce((module, current) => {
        return module.getChild(current);
      }, this.root);

      parent.addChild(path[path.length-1],newModule)
    }

    if(rawModule.modules){
      forEachValue(rawModule.modules, (rawChildModule, key) => {
        this.register(rawChildModule, path.concat(key));
      });
    }

    return newModule;
  }

  getNamespaced(path){ // [a,c] a/c
    let module = this.root;

    return path.reduce((namespaceStr, key) => {
      module = module.getChild(key)
      return namespaceStr + (module.namespaced ? key + '/' : '');
    }, '');
  }
}
